package com.tuo.service.impl;

import com.tuo.beans.Detail;
import com.tuo.beans.Stopped;
import com.tuo.service.DetailService;
import com.tuo.service.StoppedService;
import com.tuo.util.BaseServiceImpl;
import com.tuo.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.List;

/**
 * Created by tuo on 2016/1/9.
 */
@Service
public class StoppedServiceImpl extends BaseServiceImpl<Stopped> implements StoppedService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    DetailService detailService;

    @SuppressWarnings("NumericOverflow")
    @Override
    public void save(Stopped stopped) throws Throwable {
        Detail detail = this.detailService.get(stopped.getDetailId());
        if (stopped.getNumber() > (detail.getNumber() - detail.getReturnNumber())) {
            this.logger.info("报停数量大于剩余出借数量。。。");
            return;
        }
        BigDecimal unitPrice = detail.getUnitPrice();
        long diff = DateUtil.string2DateDiffIncludeST(detail.getStart(), stopped.getStop());
        switch (detail.getAlgorithm()) {
            case ONCE:
                stopped.setDayNumber(diff);
                stopped.setPrice(unitPrice.multiply(new BigDecimal(stopped.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP));
                break;
            case BYDAY:
                stopped.setDayNumber(diff);
                stopped.setPrice(unitPrice.multiply(new BigDecimal(diff)).multiply(new BigDecimal(stopped.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP));
                break;
            case BYAREA:
                stopped.setDayNumber(diff);
                stopped.setPrice(new BigDecimal(0.00));
                break;
            case FIXEDDAY:
                if (diff < Long.valueOf(detail.getParams())) {
                    diff = Long.valueOf(detail.getParams());
                }
                stopped.setDayNumber(diff);
                stopped.setPrice(unitPrice.multiply(new BigDecimal(diff)).setScale(2, BigDecimal.ROUND_HALF_UP));
                break;
        }
        super.save(stopped);
        detail.setReturnNumber(detail.getReturnNumber() + stopped.getNumber());
        if (detail.getReturnNumber() == detail.getNumber()) {
            BigDecimal price = new BigDecimal(0.00);
            detail.setStop(stopped.getStop());
            List<Stopped> stoppeds = this.query(new Stopped(detail.getId()));
            for (Stopped stop : stoppeds) {
                price = price.add(stop.getPrice());
            }
            detail.setPrice(price);
        }
        this.detailService.update(detail);
    }
}
